from flask import Flask,session,g,request,render_template,send_from_directory,send_file
import config
from exts import db
#from utils import db
from apps.views import register,login,watermark,history,webhomepage
import os
from datetime import datetime
import time
from sqlalchemy import text
from flask_cors import CORS
from flask_jwt_extended import create_access_token, jwt_required, JWTManager, get_jwt_identity


def create_app():
    app = Flask(__name__)
    CORS(app)  # 全局启用 CORS
    # session=None
    #app.secret_key = 'cwjdsz'  # 设置一个密钥来加密 session 数据


    #
    # UPLOAD_FOLDER = os.path.join('static', 'uploads')
    # app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    # DB_URI = 'mysql+pymysql://root:123456@127.0.0.1:3306/watermarkremoval?charset=utf8'
    # app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI

    jwt = JWTManager(app)
    #使用SQLAlchemy,连接成功
    app.config.from_object(config)
    print(app.config['JWT_SECRET_KEY'])
    print(app.config['JWT_ACCESS_TOKEN_EXPIRES'])
    print(app.config)
    # 是否追踪数据库修改，一般不开启, 会影响性能
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # 是否显示底层执行的SQL语句
    app.config['SQLALCHEMY_ECHO'] = True

    db.init_app(app)

    import uuid

    # 生成一个新的 UUID
    new_uuid = uuid.uuid4().hex

    # 转换为字符串形式
    uuid_str = str(new_uuid)

    print(uuid_str)
    app.register_blueprint(register.reg)
    app.register_blueprint(login.login)
    app.register_blueprint(watermark.wm)
    app.register_blueprint(history.history)
    app.register_blueprint(webhomepage.whp)
    # 创建 Flask 应用程序上下文
    with app.app_context():
        # 执行原生 SQL 查询
        sql = text('SELECT * FROM user')
        result = db.session.execute(sql)
        print(result.fetchall())


    #数据池连接,连接成功
    #result = db.fetch_one("SELECT * FROM user", None)  # 假设有一个 fetch_one 函数来执行查询
    #print(result)
    '''
    @app.before_request
    def before_request():
        if request.path.startswith("/login"):
            loginUserId = session.get('user_id')
            setattr(g,"loginUserId",loginUserId)

    @app.context_processor
    def context_processor():
        if request.path.startswith("/login"):
            return dict({"loginUserId",g.loginUserId})
    '''

    @app.route('/')
    def index():
        return render_template('webhomepage.html')



    return app